# -*- coding: utf-8 -*-
# @Time : 2024/4/30 10:23
# @Author : Zxg
# @Email : 1473858993@qq.com
# @File : basepage.py
# @Project : Luckin_Finance_Center_UI
import os.path
import time
from common.dir import screen_successful_dir, screen_error_dir
from selenium.webdriver.common.action_chains import ActionChains
from common.webdriver import driver
from selenium.webdriver.support.ui import WebDriverWait
from selenium import webdriver


class BasePage:

    def __init__(self, driver):
        self.driver = driver

    def find_ele(self, loc):  # 获取一个对象
        return self.driver.find_element(*loc)

    def find_eles(self, loc):  # 获取一组对象
        return self.driver.find_elements(*loc)

    def click(self, loc):  # 点击页面元素
        self.find_ele(loc).click()

    def send_key(self, loc, text):  # 输入内容
        self.find_ele(loc).send_keys(text)

    def hover(self, loc):  # 悬停定位
        ele = self.find_ele(loc)
        actions = ActionChains(driver)
        actions.move_to_element(ele).perform()

    def find_wait(self, loc, time):  # 显示等待
        return WebDriverWait(self.driver, time).until(lambda d: d.find_element(*loc), message='未找到元素')

    def switch_to_frame(self, loc):  # 切换iframe窗口
        """
        在iframe中切换
        :param loc: iframe的位置，可以是一下几种形式：
            -字符串：iframe的 id 或 name
            -整数：iframe的索引
            -WebElement：iframe的元素对象
        :return:
        """
        if isinstance(loc, str):
            # 判断传入内容为字符串
            self.driver.switch_to.frame(loc)
        elif isinstance(loc, int):
            # 判断传入内容为整形
            self.driver.switch_to.frame(loc)
        elif isinstance(loc, webdriver.remote.webelement.WebElement):
            # 判断传入内容为元素定位
            self.driver.switch_to.frame(loc)
        else:
            # 打印报错信息，类型不在可以兼容范围内。
            raise ValueError("Invalid loc type:{}".format(type(loc)))

    def exit_frame(self):  # 退出iframe窗口
        self.driver.switch_to.default_content()

    def switch_win(self, num):  # 切换窗口
        """
        切换窗口
        :param num: 要切换的窗口坐标，坐标根据列表元素走
        :return:
        """
        number = driver.window_handles
        driver.switch_to.window(number[num])

    def screenshot_successful(self, name):  # 执行成功，截图
        """
        用例成功截图，加上成功时间
        :param name:
        :return:
        """
        ntime = time.strftime('%Y%m%d%H%M%S', time.localtime())
        filepath = os.path.join(screen_successful_dir, '{}_{}.png'.format(name, ntime))
        driver.save_screenshot(filepath)

    def screenshot_error(self, name):  # 执行失败，截图
        """
        用例失败截图，加上失败时间
        :param name:
        :return:
        """
        ntime = time.strftime('%Y%m%d%H%M%S', time.localtime())
        filepath = os.path.join(screen_error_dir, '{}_{}.png'.format(name, ntime))
        driver.save_screenshot(filepath)
